package com.example.lxh.testinfo;

import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import adapter.MyViewpageAdapter;
import database.sqliteUtil;
import jsonbean.Quliaty;
import jsonbean.WeatherModel;
import jsonbean.WeatherModels;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class AChartEngineActivity extends AppCompatActivity implements View.OnClickListener {

    public LinearLayout chart;
    public GraphicalView chartview;
    public Map<String, Object> map = new HashMap<>();
    private TextView m_tv_temp;
    private TextView m_tv_range;
    private ViewPager m_viewpager;
    private View view1;
    private View view2;
    private View view3;
    private View view4;
    private TextView m_tv_0;
    private TextView m_tv_1;
    private TextView m_tv_2;
    private TextView m_tv_3;
    private ImageView m_imager;
    private static List<Quliaty> list = new ArrayList<>();
    private static sqliteUtil sqliteutil = null;
    List<View> listViews = new ArrayList<>();

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                showChart(map);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_achart_engine);
        initView();
        listViews.add(view1);
        listViews.add(view2);
        listViews.add(view3);
        listViews.add(view4);
        sqliteutil = new sqliteUtil(this);
        m_viewpager.setAdapter(new MyViewpageAdapter(listViews, AChartEngineActivity.this));
        m_viewpager.setOnPageChangeListener(new MyChangeListener());
        m_viewpager.setCurrentItem(0);
        m_tv_0.setBackgroundResource(R.drawable.border);
        m_tv_1.setBackgroundColor(Color.parseColor("#FFFFFF"));
        m_tv_2.setBackgroundColor(Color.parseColor("#FFFFFF"));
        m_tv_3.setBackgroundColor(Color.parseColor("#FFFFFF"));
        map = getData();
        Timer timer = new Timer();
        timer.schedule(new TimerTest(), 1000, 2000);
    }

    static class TimerTest extends TimerTask {
        @Override
        public void run() {
            getAsynHttp();
        }
    }

    private static void getAsynHttp() {
        // Okhttp 进行网络请求
        OkHttpClient client = new OkHttpClient();
        final Request requests = new Request.Builder()
                .url("http://111.231.195.53/TransportService/type/jason/action/GetAllSense.do").build();
        Call call = client.newCall(requests);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call arg0, IOException e) {
                Log.w("Lxh", "异常" + e);
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String string = response.body().string();
                Quliaty quliaty = null;
                try {
                    quliaty = new Quliaty();
                    JSONObject jsonObject = new JSONObject(string);
                    quliaty.setPm((Integer) jsonObject.get("pm2.5"));
                    quliaty.setCo2((Integer) jsonObject.get("co2"));
                    quliaty.setHumidity((Integer) jsonObject.get("humidity"));
                    quliaty.setLightIntensity((Integer) jsonObject.get("LightIntensity"));
                    quliaty.setTemp((Integer) jsonObject.get("temp"));
                    Log.w("Lxh", "Okhttp : " + string);
                    list.add(quliaty);
                    Log.w("Lxh", "list size: " + list.size());
                    if (list.size() == 20) {
                        sqliteutil.insert(list);
                        list.clear();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void initView() {
        chart = findViewById(R.id.chart);
        m_tv_temp = findViewById(R.id.tv_temp);
        m_tv_range = findViewById(R.id.tv_range);
        m_viewpager = findViewById(R.id.pager);
        m_imager = findViewById(R.id.fresh);
        LayoutInflater lf = getLayoutInflater().from(this);
        view1 = lf.inflate(R.layout.pageritemview, null);
        view2 = lf.inflate(R.layout.pageritemview, null);
        view3 = lf.inflate(R.layout.pageritemview, null);
        view4 = lf.inflate(R.layout.pageritemview, null);
        m_tv_0 = findViewById(R.id.quality);
        m_tv_1 = findViewById(R.id.temperture);
        m_tv_2 = findViewById(R.id.humidity);
        m_tv_3 = findViewById(R.id.dioxide);
        m_tv_0.setOnClickListener(this);
        m_tv_1.setOnClickListener(this);
        m_tv_2.setOnClickListener(this);
        m_tv_3.setOnClickListener(this);
        m_imager.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.quality:
                setState(0);
                break;
            case R.id.temperture:
                setState(1);
                break;
            case R.id.humidity:
                setState(2);
                break;
            case R.id.dioxide:
                setState(3);
                break;
            case R.id.fresh:
                List<Quliaty> lists = sqliteUtil.query();
                Log.w("Lxh", "查询出来的数据 ： " + lists.size());
                break;
        }
    }

    public void setState(int index) {
        if (index == 0) {
            m_viewpager.setCurrentItem(index);
            m_tv_0.setBackgroundResource(R.drawable.border);
            m_tv_1.setBackgroundColor(Color.parseColor("#FFFFFF"));
            m_tv_2.setBackgroundColor(Color.parseColor("#FFFFFF"));
            m_tv_3.setBackgroundColor(Color.parseColor("#FFFFFF"));
        } else if (index == 1) {
            m_viewpager.setCurrentItem(index);
            m_tv_1.setBackgroundResource(R.drawable.border);
            m_tv_0.setBackgroundColor(Color.parseColor("#FFFFFF"));
            m_tv_2.setBackgroundColor(Color.parseColor("#FFFFFF"));
            m_tv_3.setBackgroundColor(Color.parseColor("#FFFFFF"));

        } else if (index == 2) {
            m_viewpager.setCurrentItem(index);
            m_tv_2.setBackgroundResource(R.drawable.border);
            m_tv_1.setBackgroundColor(Color.parseColor("#FFFFFF"));
            m_tv_0.setBackgroundColor(Color.parseColor("#FFFFFF"));
            m_tv_3.setBackgroundColor(Color.parseColor("#FFFFFF"));

        } else if (index == 3) {
            m_viewpager.setCurrentItem(index);
            m_tv_3.setBackgroundResource(R.drawable.border);
            m_tv_1.setBackgroundColor(Color.parseColor("#FFFFFF"));
            m_tv_2.setBackgroundColor(Color.parseColor("#FFFFFF"));
            m_tv_0.setBackgroundColor(Color.parseColor("#FFFFFF"));
        }
    }

    public Map<String, Object> getData() {
        String url = "http://v.juhe.cn/weather/index?format=1&cityname=%e9%95%bf%e6%b2%99&key=0f701fac394d3ae9329135d766afa05d";
        final List<String> list = new ArrayList<>();
        final Map<String, Object> map = new HashMap<>();
        RequestQueue queue = Volley.newRequestQueue(AChartEngineActivity.this);
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                JsonParser parser = new JsonParser();
                JsonObject json = (JsonObject) parser.parse(response);
                JsonElement resultcode = json.get("resultcode");
                if (resultcode.getAsString().equals("200") && resultcode != null) {
                    JsonObject result = (JsonObject) json.get("result");
                    JsonObject today = (JsonObject) result.get("today");
                    JsonElement temp = today.get("temperature");
                    String str = temp.getAsString();
                    String[] temps = str.split("~");
                    String[] s = temps[0].split("℃");
                    String[] s1 = temps[1].split("℃");
                    Integer d = (Integer.parseInt(s[0]) + Integer.parseInt(s1[0])) / 2;

                    JsonObject future = (JsonObject) result.get("future");
                    WeatherModels models = gson.fromJson(future, WeatherModels.class);
                    WeatherModel m8 = models.getDay_20180117();
                    WeatherModel m9 = models.getDay_20180118();
                    WeatherModel m10 = models.getDay_20180119();
                    WeatherModel m11 = models.getDay_20180120();
                    WeatherModel m12 = models.getDay_20180121();
                    WeatherModel m13 = models.getDay_20180122();
                    list.add(m11.getTemperature());
                    list.add(m12.getTemperature());
                    list.add(m13.getTemperature());
                    list.add(m8.getTemperature());
                    list.add(m9.getTemperature());
                    list.add(m10.getTemperature());
                    List<String> listMin = new ArrayList<>();
                    List<String> listMax = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        String single = list.get(i);
                        String[] strs = single.split("~");
                        String[] tmp = strs[0].split("℃");
                        listMin.add(tmp[0]);
                        String[] tmp1 = strs[1].split("℃");
                        listMax.add(tmp1[0]);
                    }
                    map.put("min", listMin);
                    map.put("max", listMax);
                    map.put("avertemp", d);
                    map.put("today", str);
                    handler.sendEmptyMessage(1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.w("Lxh", "onErrorResponse: " + error);
            }
        });
        queue.add(request);
        return map;
    }


    private void showChart(Map<String, Object> map) {
        List<String> listMin = (List<String>) map.get("min");
        List<String> listMax = (List<String>) map.get("max");
        int min = Integer.parseInt(Collections.min(listMin));
        int max = Integer.parseInt(Collections.max(listMax));

        XYMultipleSeriesDataset mDaraset = getDataSet(map);
        XYMultipleSeriesRenderer mRefender = getRefeder(min, max);
        chartview = ChartFactory.getLineChartView(this, mDaraset, mRefender);
        chart.addView(chartview);
        m_tv_range.setText("今天：" + String.valueOf(map.get("today")));
        m_tv_temp.setText(String.valueOf(map.get("avertemp")) + "℃");
    }

    private XYMultipleSeriesRenderer getRefeder(int min, int max) {
        XYMultipleSeriesRenderer seriesRenderer = new XYMultipleSeriesRenderer();
        seriesRenderer.setChartTitleTextSize(20); //设置标题的大小
        seriesRenderer.setMargins(new int[]{40, 30, 30, 20});//设置外边距   上左下右
        seriesRenderer.setAxisTitleTextSize(20);//设置坐标轴标题的大小
        seriesRenderer.setYAxisMin(min); //y轴的起始值
        seriesRenderer.setYAxisMax(max + 1);  //最大值
        seriesRenderer.setAxesColor(Color.BLACK);
        seriesRenderer.setDisplayValues(true);
        seriesRenderer.setShowAxes(false);

        seriesRenderer.setXAxisMin(0.5); //x轴的起始值
        seriesRenderer.setXAxisMax(7.5);// x轴的最大值
        seriesRenderer.setApplyBackgroundColor(true);
        seriesRenderer.setLabelsColor(0x000000);
        seriesRenderer.setBackgroundColor(Color.WHITE);

        seriesRenderer.setZoomButtonsVisible(false);
        seriesRenderer.setZoomEnabled(false);
        seriesRenderer.setZoomInLimitX(7);
        seriesRenderer.setPanEnabled(false);
        seriesRenderer.setXLabelsAlign(Paint.Align.CENTER);
        seriesRenderer.setYLabelsAlign(Paint.Align.LEFT);
        seriesRenderer.setYLabels(5);//设置X Y轴显示的值
        seriesRenderer.setXLabels(0);
        seriesRenderer.setPointSize(2);
        seriesRenderer.setMarginsColor(Color.WHITE);
        seriesRenderer.setClickEnabled(false);

        XYSeriesRenderer xySeriesRenderer = new XYSeriesRenderer();
        xySeriesRenderer.setPointStyle(PointStyle.CIRCLE);
        xySeriesRenderer.setPointStrokeWidth(3);
        xySeriesRenderer.setColor(Color.RED);
        xySeriesRenderer.setDisplayChartValues(true);
        xySeriesRenderer.setChartValuesTextSize(14);
        xySeriesRenderer.setLineWidth(1.5f);

        XYSeriesRenderer xySeriesRenderer1 = new XYSeriesRenderer();
        xySeriesRenderer1.setPointStyle(PointStyle.CIRCLE);
        xySeriesRenderer1.setPointStrokeWidth(3);
        xySeriesRenderer1.setFillPoints(true);
        xySeriesRenderer1.setColor(Color.BLUE);
        xySeriesRenderer1.setDisplayChartValues(true);
        xySeriesRenderer1.setChartValuesTextSize(14);
        xySeriesRenderer1.setLineWidth(1.5f);

        seriesRenderer.setShowGridX(true);
        seriesRenderer.setGridColor(Color.GRAY);
        seriesRenderer.addSeriesRenderer(xySeriesRenderer);
        seriesRenderer.addSeriesRenderer(xySeriesRenderer1);
        return seriesRenderer;
    }


    public XYMultipleSeriesDataset getDataSet(Map<String, Object> map) {
        List<String> listMin = (List<String>) map.get("min");
        List<String> listMax = (List<String>) map.get("max");
        XYMultipleSeriesDataset seriesDataset = new XYMultipleSeriesDataset();

        XYSeries xySeries = new XYSeries("最高气温");
        for (int i = 1; i <= listMin.size(); i++) {
            xySeries.add(i, Double.parseDouble(listMax.get(i - 1)));
        }
        seriesDataset.addSeries(xySeries);

        XYSeries xySeries1 = new XYSeries("最低气温");
        for (int i = 0; i < listMin.size(); i++) {
            xySeries1.add(i + 1, Double.parseDouble(listMin.get(i)));
        }
        seriesDataset.addSeries(xySeries1);
        return seriesDataset;
    }

    class MyChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            setState(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }


    public XYMultipleSeriesDataset getDataSet_hist() {
        XYMultipleSeriesDataset dataSet_hist = new XYMultipleSeriesDataset();
        final int n = 15;
        Random random = new Random();
        CategorySeries series = new CategorySeries("Demo");
        for (int i = 0; i < n; i++) {
            series.add(100 + random.nextInt() % 100);
        }
        dataSet_hist.addSeries(series.toXYSeries());
        return dataSet_hist;
    }

    public XYMultipleSeriesRenderer getRefeder_hist() {
        XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
        SimpleSeriesRenderer r = new SimpleSeriesRenderer();
        r.setColor(Color.parseColor("#979797"));
        renderer.addSeriesRenderer(r);

        renderer.setZoomButtonsVisible(false);
        renderer.setZoomEnabled(false);
        renderer.setZoomInLimitX(7);
        renderer.setPanEnabled(false, false); //设置 左右滑动 ， 不许上下滑动
        renderer.setShowAxes(false);// 是否显示 坐标轴
        renderer.setYLabelsColor(0, Color.BLACK); //Y轴标签的颜色
        renderer.setLabelsTextSize(18);  //设置标签的字体大小
        renderer.setApplyBackgroundColor(true);//设置是否显示背景颜色
        renderer.setBackgroundColor(Color.WHITE);//设置背景颜色
        renderer.setMarginsColor(Color.WHITE);//设置图标周围的颜色
        renderer.setClickEnabled(true);//设置是否可点击


        renderer.setShowGridX(true); //是否显示网格  X
        renderer.setGridColor(Color.parseColor("#979797")); //设置网格颜色
        renderer.setBarSpacing(1.0); //柱子的粗细
        renderer.setYLabels(6);  //  X  Y要显示的标签
        renderer.setXLabels(10);
        renderer.setXLabelsColor(Color.BLACK);
        renderer.setMargins(new int[]{0, 20, 0, 20}); //设置外边距   上左下右
        renderer.setXTitle("x轴");
        renderer.setYTitle("Y轴");
        renderer.setXAxisMin(0.5);
        renderer.setXAxisMax(20.0);
        renderer.setYAxisMin(0);
        renderer.setYAxisMax(210);
        return renderer;
    }

}
